package com.aj.activity;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.aj.activity.adapter.HomeFragmentPagerAdapter;
import com.aj.activity.fragment.FamilyFragment;
import com.aj.activity.fragment.HomeFragment;
import com.aj.activity.fragment.SettingsFragment;
import com.aj.activity.fragment.TaskFragment;
import com.aj.application.LoveHomeApplication;
import com.aj.utils.Contants;
import com.aj.utils.StringUtils;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.applib.controller.HXSDKHelper;
import com.easemob.chat.EMMessage;

@SuppressLint({ "Override", "NewApi" })
public class HomeActivity extends FragmentActivity implements EMEventListener {
	private ViewPager mPager;
	private RadioGroup mGroup;
	private RadioButton familyRadioButton;
	private RadioButton homeRadioButton;
	private RadioButton settingsRadioButton;
	private TextView title;
	private TextView skinpeeler_button;
	private Button rightbutton_1;
	private JPushMessageReceiver mMessageReceiver;
	private LinearLayout menu_leanlayout;
	protected LinearLayout paper_all;

	public static boolean isForeground = false;
	/**
	 * 双击退出函数
	 */
	private static Boolean isExit = false;

	private ArrayList<Fragment> fragmentList;

	private String pageFlag = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		// 初始化界面组件
		initView();
		// 初始化ViewPager
		initViewPager();
		registerMessageReceiver();
		init();
		if (mPager.getCurrentItem() == 0) {
			rightbutton_1.setVisibility(View.VISIBLE);
			rightbutton_1.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = null;
					if (LoveHomeApplication.token == null
							|| LoveHomeApplication.token.trim().length() == 0) {
						intent = new Intent(Contants.LOGINACTIVITY_ACTION);
					} else {
						intent = new Intent(
								Contants.MORE_FAMILY_ACTIVITY_ACTION);
					}
					startActivity(intent);
				}
			});
		}
	}

	private void initView() {
		mPager = (ViewPager) findViewById(R.id.viewPager);
		mGroup = (RadioGroup) findViewById(R.id.radiogroup);
		familyRadioButton = (RadioButton) findViewById(R.id.rb_family);
		homeRadioButton = (RadioButton) findViewById(R.id.rb_home);
		settingsRadioButton = (RadioButton) findViewById(R.id.rb_settings);
		skinpeeler_button = (TextView) findViewById(R.id.skinpeeler_button);
		menu_leanlayout = (LinearLayout) findViewById(R.id.menu_leanlayout);
		paper_all = (LinearLayout) findViewById(R.id.paper_all);
		title = (TextView) findViewById(R.id.title);
		rightbutton_1 = (Button) findViewById(R.id.rightbutton_1);
		setActionTitile(R.string.radiobutton_myfamily);
		ButtonEvent buttonEvent = new ButtonEvent();
		skinpeeler_button.setOnClickListener(buttonEvent);
		rightbutton_1.setOnClickListener(buttonEvent);
		pageFlag = getIntent().getStringExtra(Contants.PAGEFLAG_STRING);
		// RadioGroup选中状态改变监听
		mGroup.setOnCheckedChangeListener(new myCheckChangeListener());
		mPager.setCurrentItem(0);
	}

	class ButtonEvent implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.skinpeeler_button:
				Toast.makeText(getApplicationContext(), "点击了换肤",
						Toast.LENGTH_LONG).show();
				break;
			case R.id.rightbutton_1:
				Intent intent = new Intent(Contants.MORE_FAMILY_ACTIVITY_ACTION);
				startActivity(intent);
				break;
			}
		}

	}

	private void setActionTitile(int textResID) {
		title.setText(textResID);
	}

	private void initViewPager() {
		FamilyFragment familyFragment = new FamilyFragment();
		HomeFragment homeFragment = new HomeFragment();
		TaskFragment taskFragment = new TaskFragment();
		SettingsFragment settingsFragment = new SettingsFragment();
		fragmentList = new ArrayList<Fragment>();
		fragmentList.add(familyFragment);
		fragmentList.add(homeFragment);
		fragmentList.add(taskFragment);
		fragmentList.add(settingsFragment);
		// ViewPager设置适配器
		mPager.setAdapter(new HomeFragmentPagerAdapter(
				getSupportFragmentManager(), fragmentList));
		// ViewPager页面切换监听
		mPager.setOnPageChangeListener(new myOnPageChangeListener());
		// ViewPager显示第一个Fragment
		if (pageFlag != null
				&& pageFlag.equals(Contants.REGISTER_PAGEFLAG_STRING)) {
			mPager.setCurrentItem(2);
			settingsRadioButton.setChecked(true);
		} else {
			mPager.setCurrentItem(0);
		}

	}

	/**
	 * RadioButton切换Fragment
	 */
	private class myCheckChangeListener implements
			RadioGroup.OnCheckedChangeListener {

		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.rb_family:
				// ViewPager显示第一个Fragment且关闭页面切换动画效果
				mPager.setCurrentItem(0, false);
				break;
			case R.id.rb_home:
				mPager.setCurrentItem(1, false);
				break;
			case R.id.rb_task:
				mPager.setCurrentItem(2, false);
				break;
			case R.id.rb_settings:
				mPager.setCurrentItem(3, false);
				break;
			}
		}
	}

	/**
	 * ViewPager切换Fragment,RadioGroup做相应变化
	 */
	private class myOnPageChangeListener implements
			ViewPager.OnPageChangeListener {

		@Override
		public void onPageScrolled(int position, float positionOffset,
				int positionOffsetPixels) {

		}

		@Override
		public void onPageSelected(int position) {
			switch (position) {
			case 0:
				mGroup.check(R.id.rb_family);
				setActionTitile(R.string.radiobutton_myfamily);
				rightbutton_1.setVisibility(View.VISIBLE);
				rightbutton_1.setText("更多家人");
				rightbutton_1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = null;
						if (LoveHomeApplication.token == null
								|| LoveHomeApplication.token.trim().length() == 0) {
							intent = new Intent(Contants.LOGINACTIVITY_ACTION);
						} else {
							intent = new Intent(
									Contants.MORE_FAMILY_ACTIVITY_ACTION);
						}
						startActivity(intent);
					}
				});
				break;
			case 1:
				mGroup.check(R.id.rb_home);
				setActionTitile(R.string.radiobutton_myhome);
				rightbutton_1.setVisibility(View.GONE);
				break;
			case 2:
				mGroup.check(R.id.rb_task);
				setActionTitile(R.string.radiobutton_mytask);
				rightbutton_1.setVisibility(View.VISIBLE);
				rightbutton_1.setText("管理");
				rightbutton_1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						openPanel(false);
					}
				});
				break;
			case 3:
				mGroup.check(R.id.rb_settings);
				setActionTitile(R.string.radiobutton_mysetting);
				rightbutton_1.setVisibility(View.GONE);
				break;
			}
		}

		@Override
		public void onPageScrollStateChanged(int state) {

		}
	}

	/**
	 * 菜单、返回键响应
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			exitBy2Click();
		}
		return false;
	}

	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

		} else {
			finish();
			System.exit(0);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		JPushInterface.onResume(this);
		isForeground = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		isForeground = false;
		JPushInterface.onPause(this);
	}

	public void registerMessageReceiver() {
		mMessageReceiver = new JPushMessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(Contants.MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}

	public class JPushMessageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (Contants.MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
				String messge = intent.getStringExtra(Contants.KEY_MESSAGE);
				String extras = intent.getStringExtra(Contants.KEY_EXTRAS);
				StringBuilder showMsg = new StringBuilder();
				showMsg.append(Contants.KEY_MESSAGE + " : " + messge + "\n");
				if (!StringUtils.isStringEmpty(extras)) {
					showMsg.append(Contants.KEY_EXTRAS + " : " + extras + "\n");
				}
				Toast.makeText(context, showMsg.toString(), Toast.LENGTH_LONG)
						.show();
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		JPushInterface.setAlias(HomeActivity.this, "", null);
		JPushInterface.stopPush(LoveHomeApplication.application);
		unregisterReceiver(mMessageReceiver);
	}

	// 初始化 JPush。如果已经初始化，但没有登录成功，则执行重新登录。
	private void init() {
		JPushInterface.init(getApplicationContext());
	}

	public void setMenuLayout(View view) {
		if (view != null && menu_leanlayout != null) {
			menu_leanlayout.removeAllViews();
			menu_leanlayout.addView(view, new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		}
	}

	public void openPanel() {
		openPanel(true);
	}

	public void openPanel(boolean isCoverFlag) {
		Animation anim = AnimationUtils.loadAnimation(this,
				R.anim.slide_bottom_in);
		menu_leanlayout.setVisibility(View.VISIBLE);
		if (isCoverFlag) {
			paper_all.setVisibility(View.VISIBLE);
		} else {
			paper_all.setVisibility(View.GONE);
		}
		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				menu_leanlayout.clearAnimation();
			}
		});
		menu_leanlayout.startAnimation(anim);
	}

	public void closePanel() {
		Animation anim = AnimationUtils.loadAnimation(this,
				R.anim.slide_bottom_out);
		anim.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				menu_leanlayout.setVisibility(View.GONE);
				paper_all.setVisibility(View.GONE);
				menu_leanlayout.clearAnimation();
			}
		});
		menu_leanlayout.startAnimation(anim);
	}

	@Override
	public void onEvent(EMNotifierEvent event) {
		// switch (event.getEvent()) {
		// case ChatBaseActivity.EventNewMessage: // 普通消息
		// {
		EMMessage message = (EMMessage) event.getData();
		// 提示新消息
		HXSDKHelper.getInstance().getNotifier().onNewMsg(message);

		// break;
		// }
		//
		// case EventOfflineMessage: {
		// break;
		// }
		//
		// case EventConversationListChanged: {
		// break;
		// }
		//
		// default:
		// break;
		// }
	}
}
